package pkg

import (
	"crypto/md5"
	"encoding/hex"
	"errors"
	"github.com/gin-gonic/gin"
	"github.com/toolkits/pkg/logger"
	"io"
	"regexp"
	"strings"
)

func EncryptWithMd5(srcString string) (result string) {
	h := md5.New()
	_, err := io.WriteString(h, srcString)
	if err != nil {
		logger.Error(err)
	}
	b := h.Sum(nil)

	result = hex.EncodeToString(b)
	return result
}

func CheckPassword(password string) (err error) {
	//校验密码长度
	if len(password) > 18 || len(password) < 6 {
		err = errors.New("密码必须是8~16位")
		return err
	} else {
		logger.Info(len(password), "长度检查通过")
	}

	//校验纯英文
	b, err := regexp.MatchString("^([A-z]+)$", password)
	if err != nil {
		logger.Error(err)
	}
	if b == true {
		err = errors.New("密码不能是纯英文")
		return err
	} else {
		logger.Info("纯英文检查通过")
	}

	//校验纯数字
	b, err = regexp.MatchString("^([0-9]+)$", password)
	if err != nil {
		logger.Error(err)
		return err
	}

	if b == true {
		err = errors.New("密码不能是纯数字")
		return err
	} else {
		logger.Info("纯数字检查通过")
	}
	return nil
}

// GetTokenFromC
// 从C中获取token
func GetTokenFromC(c *gin.Context) (crowToken string, err error) {

	//从c中获取token
	authorization := c.Request.Header.Get("Authorization")
	if len(authorization) == 0 {
		return crowToken, errors.New("获取token失败")
	}

	s2 := strings.SplitN(authorization, " ", 2)
	//fmt.Printf("===================%+v", s2)
	crowToken = s2[1]
	//fmt.Printf("===================%+v", strToken)

	if crowToken == "" {
		return crowToken, errors.New("获取token失败")
	}
	return crowToken, err
}
